package com.dailyblue.smbms.controller;


import com.dailyblue.smbms.bean.User;
import com.dailyblue.smbms.service.UserService;
import com.dailyblue.smbms.service.impl.UserServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;

@WebServlet("/user_login")
public class UserLoginController extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String code = request.getParameter("code");
        String password = request.getParameter("password");
        UserService service = new UserServiceImpl();
        User user = service.login(code, password);
        if (user == null) {
            // response.sendRedirect("login.html#error=1");
            request.getRequestDispatcher("login.html#error=1").forward(request, response);
        } else {
            // 保存到session
            HttpSession session = request.getSession();
            session.setAttribute("USER_INFO", user);
            // 保存到cookie
            Cookie cookie = new Cookie("USER_INFO", user.getUserName() + "");
            cookie.setMaxAge(60 * 60 * 24);
            response.addCookie(cookie);
            //response.sendRedirect("index.html");
            request.getRequestDispatcher("index.html").forward(request, response);
        }
    }
}